﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using EZMemoLib;
using System.ComponentModel;

namespace Remember.WPF.Views
{
    /// <summary>
    /// Interaction logic for BookListControl.xaml
    /// </summary>
    public partial class BookListControl : UserControl
    {
        public string catID;
        public event EventHandler OnClickBook;
        public event EventHandler OnClickEdit;
        public event EventHandler OnStart;
        public event EventHandler OnSwitchUser;

        DoubleAnimation animFadeIn = null;
        DoubleAnimation animFadeOut = null;

        public BookListControl()
        {
            InitializeComponent();

            //Build();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                animFadeIn = new DoubleAnimation();
                animFadeIn.From = 0;
                animFadeIn.To = 1;
                animFadeIn.Duration = new Duration(TimeSpan.FromMilliseconds(1600));
                this.BeginAnimation(OpacityProperty, animFadeIn);

                animFadeOut = new DoubleAnimation();
                animFadeOut.From = 1;
                animFadeOut.To = 0;
                animFadeOut.Duration = new Duration(TimeSpan.FromMilliseconds(500));

                Bind();
            }
        }

        private void Bind()
        {
            bookBus = BookBusiness.Instance();

            uiLoginName.Content = Context.Login.LoginName;

            listFlow.DisplayMemberPath = "FlowName";
            listFlow.SelectedValuePath = "FlowMark";

            listFlow.ItemsSource = Player.GetPlayFlows();

            string flow =  ConfigOp.LoadConfig (ConfigOp.CONFIGNAME_GlobalFlow);
            
            if (!string.IsNullOrEmpty(flow))
            {
                listFlow.SelectedValue = flow ;
                Context.ForceFlow = flow;
            }
            else
            {
                Context.ForceFlow = "";
                if (listFlow.Items.Count > 0)
                {
                    listFlow.SelectedIndex = 0;
                }
            }

        }

        BookBusiness  bookBus  = null;

        public void Build()
        {
            TodayBookList = MyBookList.Instance().GetMyBookList();

            var list = bookBus.GetBookList(0);

            this.uiListPanel.Children.Clear();
            var bookListTitle = new BookItemControl();
            bookListTitle.btnEdit.Visibility = System.Windows.Visibility.Collapsed;
            bookListTitle.IsEnabled = false;
            this.uiListPanel.Children.Add(bookListTitle);

            foreach (var cat in list)
            {
                bool isChecked = false;

                //find in Mybook list
                foreach (var a in TodayBookList)
                {
                    if (a.CategoryID == cat.CategoryID)
                    {
                        if (a.Status > 0)
                        {
                            isChecked = true;
                        }
                        break;
                    }
                }

                if (uiShowAllBooks.IsChecked != null && uiShowAllBooks.IsChecked.Value)
                {

                }
                else
                {
                    if (!isChecked)
                    {
                        continue;
                    }
                }

                cat.ItemTotal = bookBus.StatBookItemTotal(cat.CategoryID);

                var bookItem = new BookItemControl();
                bookItem.OnClickTitle += new EventHandler(bookItem_OnClickTitle);
                bookItem.OnClickEdit += new EventHandler(bookItem_OnClickEdit);


                bookItem.checkBoxStatus.IsChecked = isChecked;

                bookItem.Tag = cat;
                bookItem.catID = cat.CategoryID.ToString();

                bookItem.uiBookName.Text = cat.CategoryName;
                bookItem.uiBookName.Tag = cat.CategoryID.ToString();


                if (cat.ItemTotal != null)
                {
                    bookItem.uiTotal.Text = cat.ItemTotal.Value.ToString();
                }

                string loginID = (Context.Login != null) ? Context.Login.LoginID : string.Empty;


                bookItem.uiNew.Text = "0";
                if (cat.ItemPlan != null)
                {
                    bookItem.uiNew.Text = cat.ItemPlan.Value.ToString();
                }

                var player = new Player(loginID, cat.CategoryID);

                //clear before today
                player.DrillClear();

                player.EstimateTodayList();

                bookItem.uiRepetitions.Text = player.RepetitionToday.ToString();
                bookItem.uiNew.Text = player.NewToday.ToString();
                bookItem.uiDrills.Text = player.DrillToday.ToString();

                //bookItem.uiDrills.Text = "0";

                //var drilllist = player.DrillList();
                //if (drilllist != null)
                //{
                //    cat.ItemDrill = (long)drilllist.Count;
                //}
                //if (cat.ItemDrill != null)
                //{
                //    bookItem.uiDrills.Text = cat.ItemDrill.Value.ToString();
                //}



                //if (cat.ItemDone != null)
                //{
                //    bookItem.uiDone.Text = cat.ItemDone.Value.ToString();
                //}
                //else
                {
                    bookItem.uiDone.Text = string.Format("{0}", player.GetHistoryDoneByBook(cat.CategoryID));
                }


                bookItem.btnEdit.Tag = cat.CategoryID.ToString();

                this.uiListPanel.Children.Add(bookItem);
            }
        }

        void bookItem_OnClickEdit(object sender, EventArgs e)
        {
            if (sender != null)
            {
                string bookID = sender as string;
                if (OnClickEdit != null)
                {
                    OnClickEdit(bookID, null);
                }
            }
            
        }

        void bookItem_OnClickTitle(object sender, EventArgs e)
        {
            if (sender != null)
            {
                string bookID = sender as string;
                if (OnClickBook != null)
                {
                    OnClickBook(bookID, null);
                }
            }
        }

        List<MyBookModel> TodayBookList;

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            foreach (BookItemControl bic in this.uiListPanel.Children)
            {
                if (bic.checkBoxStatus.IsChecked != null && bic.checkBoxStatus.IsChecked.Value)
                {
                    MyBookList.Instance().SaveMyBook(bic.Tag as MemoCategory, 1);
                }
                else
                {
                    MyBookList.Instance().SaveMyBook(bic.Tag as MemoCategory, 0);
                }
            }

            //reload mybook list when the status be changed
            TodayBookList = MyBookList.Instance().GetMyBookList();

            if (OnStart != null)
            {
                long firstBookID = -1;

                if (TodayBookList != null && TodayBookList.Count > 0)
                {
                    foreach (var book in TodayBookList)
                    {
                        if (book.Status > 0)
                        {
                            firstBookID = book.CategoryID;
                        }
                    }
                }

                if (firstBookID > 0)
                {
                    OnStart(firstBookID.ToString(), null);
                }
                else
                {
                    MessageBox.Show("Please select a book to start.");
                }
            }
        }

        public MyBookModel GetNextBook(long currentBookID)
        {
            MyBookModel nextBook = null;

            if (currentBookID < 0)
                return nextBook;

            bool foundCurrent = false;
            
            foreach (var book in TodayBookList)
            {
                if (foundCurrent)
                {
                    nextBook = book;
                    break;
                }
                if (book.CategoryID == currentBookID)
                {
                    foundCurrent = true;
                }
            }

            return nextBook;
        }

        private void listFlow_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            

        }

        private void listFlow_LostFocus(object sender, RoutedEventArgs e)
        {
            if (listFlow.SelectedIndex >= 0)
            {
                string globalFlow = listFlow.SelectedValue.ToString();
                if (Context.ForceFlow != globalFlow)
                {
                    Context.ForceFlow = globalFlow;
                    ConfigOp.SaveConfig(ConfigOp.CONFIGNAME_GlobalFlow, Context.ForceFlow);
                }
            }
        }

        private void btnSwitchUser_Click(object sender, RoutedEventArgs e)
        {
            if (OnSwitchUser != null)
            {
                OnSwitchUser(sender, e);
            }
        }

        private void btnCreateabook_Click(object sender, RoutedEventArgs e)
        {
            if (OnClickEdit != null)
            {
                //new book
                int bookID = -1;
                OnClickEdit(bookID, null);
            }
        }

        private void uiShowAllBooks_Click(object sender, RoutedEventArgs e)
        {
            Build();
        }

    }
}
